layui.use(['form', 'admin', 'ax', 'table'], function () {
    var form = layui.form;
    var $ax = layui.ax;
    var admin = layui.admin;
    var table = layui.table;

    var Current = {
        tableId: "table",
    };

    Current.initColumn = function () {
        return [[
            {type: 'numbers'},
            {field: 'id', hide: true, title: 'id'},
            {
                field: 'code', title: '类型', templet: function (d) {
                    let code = d.code;
                    if (code === 'ali') {
                        return "支付宝支付";
                    } else if (code === 'wx') {
                        return "微信支付";
                    }
                }
            },
            {field: 'name', title: '名称'},
            {field: 'description', title: '说明'},
            {field: 'parameterJson', title: '参数信息'},
            {
                field: 'status',
                title: '状态<i class="layui-icon layui-icon-help" style="cursor: pointer;color: orange;" onmouseover="showTips(this)" onmouseout="closeTips()"></i>',
                templet: '#statusTpl'
            },
            {field: 'createdTime', title: '创建时间'},
            {align: 'center', toolbar: '#tableBar', title: '操作', minWidth: 400}
        ]];
    };
    var tipsLayer;
    window.showTips = function (t) {
        const content = '同一类型的模板同时只会开启一个'
        //小tips
        tipsLayer = layer.tips(content, t, {
            tips: [1, '#8f8f8f'],
            time: 4000000
        })
    }

    window.closeTips = function () {
        layer.close(tipsLayer);
    }

    Current.search = function () {
        var queryData = {
            queryName: $('#name').val()
        };
        table.reload(Current.tableId, {where: queryData});
    };

    Current.onAdd = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '新增',
            area: ['60%', '70%'],
            content: system.contextPath + '/admin/payConfig/add',
            end: function () {
                admin.getTempData('formOk') && table.reload(Current.tableId);
            }
        });
    };

    Current.onEdit = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '编辑',
            area: ['60%', '70%'],
            content: system.contextPath + '/admin/payConfig/edit?id=' + data.id,
            end: function () {
                admin.getTempData('formOk') && table.reload(Current.tableId);
            }
        });
    };

    Current.onDelete = function (data) {
        var operation = function () {
            var ajax = new $ax(system.contextPath + "/api/pay.config.delete", function (res) {
                if (res.status) {
                    system.success("删除成功!");
                    table.reload(Current.tableId);
                } else {
                    system.error("删除失败!" + res.msg + "!");
                }
            }, function (res) {
                system.error("删除失败!" + res.msg + "!");
            });
            ajax.set({id: data.id});
            ajax.start();
        };
        system.confirm("是否删除" + data.name + "?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Current.tableId,
        url: system.contextPath + '/api/pay.config.page',
        page: true,
        request: {
            pageName: 'pageIndex' //页码的参数名称，默认：page
            , limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },
        height: "full-158",
        cellMinWidth: 100,
        cols: Current.initColumn(), parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.data.total, //解析数据长度
                "data": res.data.records //解析数据列表
            };
        }
        , response: {
            statusCode: 200
        }
        , size: 'lg',
        done: function (res, curr, count) {
            count || this.elem.next('.layui-table-view').find('.layui-table-header').css('overflow', 'visible');
            $('.layui-table-body').find('div.layui-table-cell').find('select').each(function () {
                var $this = $(this);
                var val = $this.data('value');
                var text;
                $(this).children().each(function () {
                    if (val == this.value) {
                        text = this.text;
                        return;
                    }
                })
                //更新layui 选择器输入框的值
                $this.next().find('.layui-select-title').find('input').val(text);
                //更新layui 选择器的值 以及设置其样式
                $this.val(val).parents('div.layui-table-cell').css('overflow', 'visible');
            })
            form.render(null, 'table');
        }
    });

    // 搜索按钮点击事件
    $('#btnAdd').click(function () {
        Current.onAdd();
    });

    //搜索按钮点击事件
    $('#btnSearch').click(function () {
        Current.search();
    });


    // 工具条点击事件
    table.on('tool(' + Current.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'delete') {
            Current.onDelete(data);
        } else if (layEvent === 'edit') {
            Current.onEdit(data);
        }
    });

    // 监听修改update到表格中
    form.on('select(statusFilter)', function (data) {
        var $elem = $(data.elem);
        if ($elem.attr("data-value") != data.value) {
            updateBatchById({
                status: data.value
                , id: $elem.attr("data-id")
                , code: $elem.attr("data-code")
            });
        }
    });


    function updateBatchById(data) {
        var ajax = new $ax(system.contextPath + "/api/pay.config.update", function (res) {
            if (res.code == 200) {
                system.success("修改成功！");
                //重新加载表格
                table.reload(Current.tableId)
            } else {
                system.error("失败：" + res.msg);
            }
        }, function (res) {
            system.error("失败：" + res.msg);
        });
        ajax.set(data);
        ajax.start();
    }
});
